#ifndef __TcpConnection_H__
#define __TcpConnection_H__
#include "InetAddress.h"
#include "Socket.h"
#include "SocketIO.h"
#include "TLV.h"

#include <memory>
#include <functional>

namespace wd
{

class EventLoop;
class TcpConnection;
using TcpConnectionPtr =std::shared_ptr<TcpConnection>;
using TcpConnectionCallback=std::function<void(TcpConnectionPtr)>;


class TcpConnection
//当TcpConnection继承了辅助类后，就拥有了shared_from_this()成员函数
//该函数可以通过this指针获取到本对象的智能指针shared_ptr
: public std::enable_shared_from_this<TcpConnection>
{
public:
    TcpConnection(int fd, EventLoop *);
    ~TcpConnection();

    bool isClosed() const;
    string receive();
    void send(const string & msg);
    void sendInLoop(const string & msg);
    string toString() const;
    void shutdown();
    int getfd();

    void sendInLoop(const TLV& tlv);  // 新增：TLV 版本的线程安全发送
    bool readPacket(Packet& packet);  // 新增：读取 TLV 并解析为 Packet

    //三个函数对象的注册
    void setAllCallbacks(const TcpConnectionCallback & cb1,
                         const TcpConnectionCallback & cb2,
                         const TcpConnectionCallback & cb3)
    {
        _onConnection = cb1;
        _onMessage = cb2;
        _onClose = cb3;
    }

    void handleNewConnectionCallback();
    void handleMesssageCallback();
    void handleCloseCallback();
private:
    //新增：实际发送 TLV 的私有函数（IO 线程执行）   
    void sendTLV(TLV& tlv);
private:
    InetAddress getLocalAddr();
    InetAddress getPeerAddr();

private:
    Socket      _sock;
    SocketIO    _sockIO;
    InetAddress _localAddr;
    InetAddress _peerAddr;
    bool        _isShutdownWrite;
    EventLoop * _loop;

    TcpConnectionCallback _onConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;
};


}//end of namespace wd


#endif

